package poc.bcsoi.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.SortedSet;
import java.util.TreeSet;

public class FileReaderUtils {
	
	public String readFileAsString(String filePath) {
		StringBuffer fileData = new StringBuffer(1000);
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(filePath)));			
			char[] buf = new char[1024];
			int numRead = 0;
			
			while ((numRead = reader.read(buf)) != -1) {
				String readData = String.valueOf(buf, 0, numRead);
				fileData.append(readData);
				buf = new char[1024];
			}

			reader.close();
			
		} catch (IOException e) {
			System.out.println("Error Reading file from " + filePath);
			e.printStackTrace();
		}
		return fileData.toString();
	}


	// Read file into a sorted array, duplicate entries will be discarded
	public static String[] loadFileAsSortedArray(final String f) {
		String thisLine;
		final SortedSet<String> s = new TreeSet<String>();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(f));
			while ((thisLine = br.readLine()) != null)
				s.add(thisLine.trim());
		} catch (IOException ioe) {
			System.err.println("Error reading file " + f);
			throw new RuntimeException(ioe);
		} finally {
			if (br != null)
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return s.toArray(new String[s.size()]);
	}

}